import React, {forwardRef, MutableRefObject, useImperativeHandle, useRef, useState} from "react";
import {Modal, ModalProps} from "antd";
import {ActionType, EditableProTable, ProColumns} from "@ant-design/pro-components";
import {Commodities, CommodityColumns} from "@/mock/commodities";
import styles from './index.module.scss';
import {Commodity} from "@/types/commodity";

const OperationTable = forwardRef((props: ModalProps, ref) => {

  const [dataSource, setDataSource] = useState<Commodity[]>(Commodities);
  const [creatable, setCreatable] = useState(false);
  const [open, setOpen] = useState(false);
  const actionRef = useRef<ActionType>(null) as MutableRefObject<ActionType | null>;
  const columns: ProColumns<Commodity>[] = [
    ...CommodityColumns,
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.key);
          }}
        >
          编辑
        </a>
      ],
    },
  ];

  const editableKey = useRef<string>();
  useImperativeHandle(ref, () => ({
    open(handInput?: boolean) {
      if (handInput) {
        setDataSource([]);
        setCreatable(true);
        setTimeout(() => {
          const key = editableKey.current = (Math.random() * 1000000).toFixed(0);
          actionRef.current?.addEditRecord?.({
            key,
            name: '',
            sell: '',
            address: '',
            price: '',
          });
        });
      } else {
        setDataSource(Commodities);
        setCreatable(false);
        editableKey.current && actionRef.current?.cancelEditable(editableKey.current);
      }
      setOpen(true);
    }
  }));

  function highlightRow(record: any) {
    // 假设我们想要高亮 age 等于 42 的行
    return record.sell === '300' ? styles.highlightedRow : '';
  }

  function getActionRef(ref: ActionType) {
    actionRef.current = ref;
  }

  return (
    <Modal width={700} height={500} title='库存操作表' open={open} onCancel={() => setOpen(false)} {...props}>
      <EditableProTable<Commodity>
        bordered
        actionRef={getActionRef}
        recordCreatorProps={
          creatable ? {
            position: 'bottom',
            record: () => ({key: (Math.random() * 1000000).toFixed(0), name: '', sell: '', address: '', price: ''}),
          } : false
        }
        editable={{
          onValuesChange: (record, recordList) => {
            setDataSource(recordList);
          },
          actionRender: (row, config, defaultDoms) => {
            return [
              defaultDoms.save,
              defaultDoms.cancel,
            ];
          }
        }}
        rowKey={'key'}
        scroll={{y: 400}}
        size={'small'}
        value={dataSource}
        columns={columns}
        rowClassName={highlightRow}
        pagination={false}
        locale={{emptyText: null}}
      />
    </Modal>
  );

});


export default OperationTable;
